#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT 8888
#define SERVER_IP "192.168.152.130"
#define BUFFER_SIZE 1024

int main(int argc, char const *argv[])
{
    //创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1){
        perror("socket创建失败：");
        return -1;
    }

    //配置服务器地址信息
    struct sockaddr_in serverInfo;
    memset(&serverInfo, 0, sizeof(serverInfo));
    serverInfo.sin_family = AF_INET;
    serverInfo.sin_port = htons(PORT);
    serverInfo.sin_addr.s_addr = inet_addr(SERVER_IP);
    
    //发送数据
    char message[] = "hello,UDP Server!";
    ssize_t ret_sendto = sendto(sockfd, message, strlen(message), 0, (struct sockaddr*)&serverInfo, sizeof(serverInfo));
    if (ret_sendto == -1){
        perror("sendto发送失败：");
        close(sockfd);
        return -1;
    }

    printf("已经发送信息：%s\n", message);

    //接收回显信息
    char buffer[BUFFER_SIZE] = {0};
    struct sockaddr_in formInfo;
    socklen_t formInfoLen = sizeof(formInfo);
    ssize_t ret_recvfrom = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&formInfo, &formInfoLen);
    if (ret_recvfrom == -1){
        perror("recvfrom接收失败：");
    }else{
        buffer[ret_recvfrom] = '\0';
        printf("服务器回显：%s\n", buffer);
    }

    close(sockfd);

    return 0;
}
